import { localstorageDao } from './../../utils/localstorage';
import { AppStore } from './../../services/appStore';
import { NavigateService } from './../../services/navigate';
import { Component, Directive, ElementRef, OnInit, EventEmitter } from '@angular/core';
import { range } from 'lodash'
import { loadingMask } from "app/components/loadmask";


@Component({
    styleUrls: ['./initialization.scss'],
    template: `
        <div  class="connectLDc-contaiiner">
            <header>
                <i class="material-icons back divvma" (click)="onBack()">arrow_back</i>
                <h1 class="padding">连接本地数据中心</h1>
                <div class="nav">
                    <i ></i>
                    <i class="active">2</i>
                    <i ></i>
                    <i ></i>
                    <i ></i>
                </div>
            </header>
            <div class="margin">
                <dl class="instruction">
                    <dt>使用厨房显示系统，需在收银台开启数据中心</dt>
                    <dd>1.在收银台中进入 "设置 -> 本地数据中心"</dd>
                    <dd>2.点击 "设置本终端为 '本地数据中心' 主机" 按钮设置收银台为本地数据中心</dd>
                    <dd>3.点击 "配置服务"， 勾选 "门店业务服务" 并确定</dd>
                </dl>
            </div>
           
            <div class="status margin" >
                <div class="input" *ngIf='checkStatus=="input"'>
                    <div class="title">手动设定本地数据中心</div>
                    <input placeholder="输入ip地址" [(ngModel)]="LDCIp" maxLength="100" />
                    <div>
                        <button (click)="findLDC()">确定连接</button>
                        <button class="auto_search" (click)="autoSearch()">自动查找</button>
                    </div>
                </div>
                <div class="checking" *ngIf='checkStatus=="checking"'>
                     <div class="title" style="margin-bottom:30px;">正在连接本地数据中心</div>
                     <md-progress-bar mode="indeterminate" class="demo-progress-bar-margins"></md-progress-bar>
                     <!-- <button class="cancel" (click)="onNextClick()" >取消</button> -->
                </div>
                <div class="failed" *ngIf='checkStatus=="failed"'>
                    <div class="title">手动设定本地数据中心</div>
                    <input placeholder="手动设定本地数据中心" [(ngModel)]="LDCIp" maxLength="100" />
                    <div class="warn">不能连接到本地数据中心（{{LDCIp}}）</div>
                    <button class="cancel" (click)="reCheck()" >重新连接</button>
                </div>
            </div>
        </div>
    `,
    providers: []
})


export class ConnectLDC implements OnInit {
    constructor(
        private appStore: AppStore,
        private navSvr: NavigateService,
    ) {

    }
    private LDCIp = "";
    private checkStatus: string = "input";
    private system;
    private event = new EventEmitter<any>();
    async ngOnInit() {
        if (!localstorageDao.get("preLDCs")) {
            this.autoSearch();
        }
    }
    stop() {
        this.event.emit();
    }
    reCheck() {
        this.findLDC()
    }
    onBack() {
        this.stop();
        this.navSvr.navigate(["initialization/welcome"])
    }
    getLDCsFoundedResult(): Promise<any[]> {
        return new Promise(async (resove, reject) => {
            this.event.subscribe(() => {
                reject();
            })
            const ipAhead = this.getHeadIp();
            var found = (await Promise.all(range(0, 255).map(async (i) => {
                try {
                    const ip = ipAhead + "." + i;
                    const storeId = (await this.appStore.systemStore.actions.findLDC(ip, {
                        timeout: 15000
                    })).storeId;
                    return { storeId, ip }
                } catch (e) {
                    return
                }
            }))).filter(x => x);
            if (found.length > 0) {
                resove(found);
            } else {
                reject();
            }
        })
    }

    async autoSearch() {
        try {
            this.checkStatus = "checking";
            const found = await this.getLDCsFoundedResult();
            localstorageDao.set("preLDCs", found)
            this.findLDCSuccess();
        } catch (error) {
            this.checkStatus = "failed";
        }
    }

    getHeadIp() {
        let ip = (<any>window).device.getDeviceInfo().ip || "172.16.255.129";
        let index = ip.lastIndexOf(".");
        let ipAhead = ip.substring(0, index);
        return ipAhead;
    }


    findLDCSuccess() {
        setTimeout(function () {
            this.checkStatus = "passed";
            this.navSvr.navigate(["initialization/checkEnv"])
        }.bind(this), 1000);
    }

    async findLDC() {
        try {
            this.checkStatus = "checking";
            const storeId = (await this.appStore.systemStore.actions.findLDC(this.LDCIp)).storeId;
            const ip = this.LDCIp;
            localstorageDao.set("preLDCs", [{ storeId, ip }])
            this.findLDCSuccess();
        } catch (error) {
            this.checkStatus = "failed";
        }

    }
    private onNextClick() {

    }
}
